/**
 * 用tee()函数实现tee程序；输出到终端的同时，输出到一个文件；
 * @author sundx
 * @date 2020/05/07
 */

#include <assert.h>
#include <fcntl.h>
#include <iostream>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  //   char *test;
  //   std::cin >> test;
  int ret = -1;
  int pipeOut[2];
  int pipeFile[2];
  ret = pipe(pipeOut);
  assert(ret != -1);
  ret = pipe(pipeFile);
  assert(ret != -1);
  const char *filename = "test_tee.txt";
  int fileFd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0666);
  assert(fileFd > 0);
  ret = splice(STDIN_FILENO, NULL, pipeOut[1], NULL, 32768,
               SPLICE_F_MOVE | SPLICE_F_MORE);
  if (ret == -1) {
    std::cout << strerror(errno) << errno << std::endl;
    exit(1);
  };
  ret = tee(pipeOut[0], pipeFile[1], 32768, SPLICE_F_NONBLOCK);
  assert(ret != -1);

  ret = splice(pipeFile[0], NULL, fileFd, NULL, 32768,
               SPLICE_F_MOVE | SPLICE_F_MORE);
  assert(ret != -1);

  ret = splice(pipeOut[0], NULL, STDOUT_FILENO, NULL, 32768,
               SPLICE_F_MOVE | SPLICE_F_MORE);
  assert(ret != -1);

  std::cout << "ceshio" << std::endl;
  close(fileFd);
  close(pipeFile[0]);
  close(pipeFile[1]);
  close(pipeOut[0]);
  close(pipeOut[1]);
  return 0;
}